//ssc install asreg

//ffc4
//encode cusip, gen(firm)
xtset firm quarter

sort firm quarter 

asreg qlogxret logeigcen, fmb

asreg qlogxret logeigcen angvol mktrf smb hml mom, fmb


//20240908 fmb for connectedness quartiles
//encode cusip, gen(firm)
xtset firm qrank

sort firm qrank 

forvalues i = 1/4 {
    asreg qlogxret logeigcen if fcap_decile == `i', fmb
    asreg qlogxret logeigcen angvol mktrf smb hml mom if fcap_decile == `i', fmb
}

//significant logeigcen beta in lowest and highest quartiles



















/////unused
//predict fitted
asreg qlogxret logstkfcap angvol, fmb
asreg qlogxret logstkfcap angvol dm1, fmb

//manually compute omitted alpha of asreg qlogxret logstkfcap angvol vix dm1, fmb
* Step 1: Identify unique time periods in the data
levelsof quarter, local(quarters)
display "`quarters'"

* Step 2: Perform Time-Series Regressions
foreach t of local quarters {
    regress qlogxret logstkfcap angvol vix dm1 if quarter == `t'
    
    * Generate predictions
    predict xb`t', xb
    
    * Store intercept (_cons) as alpha`t'
    gen alpha`t' = _b[_cons]
    
    * Verify the content of alpha`t'
    * List alpha`t' for the current quarter `t`
    list alpha`t' if quarter == `t'
}


* Step 3: Collect Alphas and Calculate the Average Alpha
gen alpha = .
foreach t of local quarters {
    replace alpha = alpha`t' if quarter == `t'
}

* Check if alpha is populated correctly
list alpha if alpha != .

* Calculate the average alpha
egen avg_alpha = mean(alpha)

* Step 4: Compute Standard Error and T-Statistic for Alpha
gen alpha_diff = alpha - avg_alpha
gen alpha_diff_sq = alpha_diff^2
egen var_alpha = mean(alpha_diff_sq)
gen se_alpha = sqrt(var_alpha / `: word count `quarters'')

* Check intermediate values
list alpha_diff alpha_diff_sq var_alpha se_alpha if alpha != .

* Step 5: Calculate T-Statistic and P-Value
gen t_alpha = avg_alpha / se_alpha
gen p_value = 2 * invttail(`: word count `quarters'' - 1, abs(t_alpha))

* Check t_alpha and p_value
list t_alpha p_value if alpha != .

* Step 6: Display Results
display "Fama-MacBeth Alpha: " avg_alpha
display "Standard Error: " se_alpha
display "T-Statistic: " t_alpha
display "P-Value: " p_value
